package com.ljz.untils;

import java.sql.*;
import java.util.List;

public class DBUtils1 {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/bylianxi";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "Au7989l";

    public static Connection getConn() {
        try {
            Class.forName(DRIVER);
            Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            return conn;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static int exceUpdate(String sql, List<Object> list){

        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConn();
            if (conn != null) {
                ps = conn.prepareStatement(sql);
            }
            for (int i = 0; i < list.size(); i++) {
                ps.setObject(i+1,list.get(i));
            }
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(null,ps,conn);
        }
    }

    public static void closeAll(ResultSet rs,PreparedStatement ps,Connection conn){
        try {
            if (rs!=null)
                rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (ps!=null)
                ps.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (conn!=null)
                conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
